package com.ustze.ocr.type.ali.service;

import cn.hutool.core.bean.BeanUtil;
import com.aliyun.ocr_api20210707.models.RecognizeTableOcrResponse;
import com.aliyun.tea.TeaException;
import com.ustze.ocr.ocrtype.enums.OcrType;
import com.ustze.ocr.ocrtype.request.OcrRequest;
import com.ustze.ocr.type.ali.utils.AliOcrUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AliOcrService implements OcrRequest {

    private final AliOcrUtils aliOcrUtils;

    @Override
    public Map<String, Object> ocrTable(MultipartFile file) {
        com.aliyun.ocr_api20210707.Client client = aliOcrUtils.createClient();
        com.aliyun.ocr_api20210707.models.RecognizeTableOcrRequest recognizeTableOcrRequest = null;
        try {
            recognizeTableOcrRequest = new com.aliyun.ocr_api20210707.models.RecognizeTableOcrRequest()
                    .setBody(file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            RecognizeTableOcrResponse resp = client.recognizeTableOcrWithOptions(recognizeTableOcrRequest, runtime);
            return BeanUtil.beanToMap(AliOcrUtils.buildVo(resp.body.data));

        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

    @Override
    public OcrType ocrType() {
        return OcrType.ALI;
    }
}
